package com.MoveEat.activities;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.MoveEat.R;
import com.MoveEat.Utils.Consts;
import com.MoveEat.Utils.Utils;
import com.MoveEat.activities.adapters.RestDataAdapter;
import com.MoveEat.items.RestData;
import com.facebook.android.Facebook;

public class LocationActivity extends ActivityWrapper
{

	protected LocationManager			locationManager;
	protected LocationListener			mLocationListener;
	protected ListView					mLstText;

	RestDataAdapter						mArrayAdapter;

	private double						mLongitude;
	private double						mLatitude;

	ArrayList<RestData>					restInfo;
	private Facebook					mFacebook;
	private Context						mContext;

	private int							mMoveEatUID;
	private String						mJsonRestList;

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		// Handle item selection
		switch (item.getItemId())
		{
			case R.id.Exit:
				finish();
				return true;
			case R.id.refresh:
				restInfo.clear();
				mJsonRestList = null;
				getRestByLocation();
				return true;

			default:
				return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		mFacebook.authorizeCallback(requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location_layout);
		mContext = getApplicationContext();
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		mMoveEatUID = prefs.getInt(Consts.Extras.ME_UID, -1);

		mLstText = (ListView) findViewById(R.id.lstText);
		restInfo = new ArrayList<RestData>();
		mArrayAdapter = new RestDataAdapter(mContext, R.layout.listitems, restInfo);
		mLstText.setAdapter(mArrayAdapter);
		mLstText.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				Intent intent = new Intent(mContext, NewRestActivity.class);
				long restId = (Long) arg1.getTag(R.layout.listitems);
				intent.putExtra(Consts.Extras.REST_ID, restId);
				intent.putExtra(Consts.Extras.CATS, mCatHashMap);
				intent.putExtra(Consts.Extras.ME_UID, mMoveEatUID);
				if (locationManager != null)
				{
					locationManager.removeUpdates(mLocationListener);
				}
				LocationActivity.this.startActivity(intent);

			}
		});
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onResume()
	{
		super.onResume();
		Intent intent = getIntent();
		if (intent.hasExtra(Consts.Extras.SEARCH_RESULTS))
		{
			String body = intent.getStringExtra(Consts.Extras.SEARCH_RESULTS);
			mCatHashMap = (HashMap<Integer, String>) intent.getSerializableExtra(Consts.Extras.CATS);
			JSONObject obj = null;
			try
			{
				obj = new JSONObject(body);
			}
			catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (obj != null)
			{
				restInfo.clear();
				LocationActivity.this.removeDialog(ProgressDialog.STYLE_HORIZONTAL);
				JSONArray arr = obj.optJSONArray("restaurants");
				displayData(arr);
			}
		}
		else
		{
			getRestByLocation();
		}

	}

	private void getRestByLocation()
	{
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mLocationListener = new LocationListener()
		{

			@Override
			public void onLocationChanged(Location location)
			{
				try
				{
					showCurrentLocation();
					locationManager.removeUpdates(mLocationListener);
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}

			@Override
			public void onProviderDisabled(String provider)
			{
			}

			@Override
			public void onProviderEnabled(String provider)
			{
			}

			@Override
			public void onStatusChanged(String provider, int status, Bundle extras)
			{
			}
		};
		if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
		{
			LocationActivity.this.removeDialog(ProgressDialog.STYLE_HORIZONTAL);
			buildAlertMessageNoGps();
		}
		else
		{
			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Consts.MINIMUM_TIME_BETWEEN_UPDATES,
					Consts.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);

			showCurrentLocation();
			if (TextUtils.isEmpty(mJsonRestList))
			{
				SendLocInfo();
			}
		}
	}

	private void launchGPSOptions()
	{
		Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		startActivity(intent);
	}

	private void buildAlertMessageNoGps()
	{
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.gpd_disabled_dialog).setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener()
		{
			public void onClick(final DialogInterface dialog, final int id)
			{
				launchGPSOptions();
			}
		}).setNegativeButton("No", new DialogInterface.OnClickListener()
		{
			public void onClick(final DialogInterface dialog, final int id)
			{
				dialog.cancel();
			}
		});
		final AlertDialog alert = builder.create();
		alert.show();

	}

	protected void showCurrentLocation()
	{
		Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

		if (location != null)
		{
			this.mLatitude = location.getLatitude();
			this.mLongitude = location.getLongitude();
		}
	}

	protected void displayData(JSONArray arr)
	{

		for (int i = 0; i <= arr.length() - 1; i++)
		{
			JSONObject rest = arr.optJSONObject(i);
			String phone2 = "";
			String iconUrl = "";
			BitmapDrawable iconDraw = null;
			long id = rest.optLong(Consts.DB_COLUMNS.ID);
			String name = rest.optString(Consts.DB_COLUMNS.NAME);
			String address = rest.optString(Consts.DB_COLUMNS.STREET) + " " + rest.optString(Consts.DB_COLUMNS.STREET_NUM) + ", "
					+ rest.optString(Consts.DB_COLUMNS.CITY);
			String phone = rest.optString(Consts.DB_COLUMNS.PHONE);
			if (rest.optString(Consts.DB_COLUMNS.SECONDARY_PHONE) != null) phone2 = rest.optString(Consts.DB_COLUMNS.SECONDARY_PHONE);
			if (rest.optString(Consts.DB_COLUMNS.ICON_URL) != null)
			{
				iconUrl = rest.optString(Consts.DB_COLUMNS.ICON_URL);
			}
			if (iconUrl == null || iconUrl.equals("null"))
			{
				iconUrl = null;
			}

			// Utils.log("iconUrl = "+iconUrl);
			restInfo.add(new RestData(id, name, address, phone, phone2, iconUrl, iconDraw));
			mArrayAdapter.setNewList(restInfo);
			mArrayAdapter.notifyDataSetChanged();
		}

	}

	private void SendLocInfo()
	{
		new AsyncTask<Void, String, String>()
		{

			@Override
			protected void onPreExecute()
			{
				LocationActivity.this.showLoading(this);
			}

			@Override
			protected String doInBackground(Void... arg0)
			{
				getAllCategories();
				mJsonRestList = Utils.preformRequest(Utils.BASE_URL + "GetRestDetails.php?x=" + mLongitude + "&y=" + mLatitude);
				return mJsonRestList;
			}

			@Override
			protected void onPostExecute(String body)
			{
				JSONObject obj = null;
				if (body != null)
				{
					Utils.log(2,body);
					try
					{
						obj = new JSONObject(body);
					}
					catch (JSONException e)
					{
						LocationActivity.this.removeDialog(ProgressDialog.STYLE_HORIZONTAL);
						e.printStackTrace();
					}
				}
				if (obj != null)
				{
					LocationActivity.this.removeDialog(ProgressDialog.STYLE_HORIZONTAL);
					JSONArray arr = obj.optJSONArray("restaurants");
					displayData(arr);
				}
			}

		}.execute();

	}

	

	@Override
	protected void onDestroy()
	{
		if (locationManager != null)
		{
			locationManager.removeUpdates(mLocationListener);
		}
		super.onDestroy();
	}

	@Override
	public void onPause()
	{
		if (locationManager != null)
		{
			locationManager.removeUpdates(mLocationListener);
		}
		super.onPause();
	}

}